﻿using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;

namespace Identity
{
    public static class MemberQueryHelper
    {
        private static string _adminRoleId;
        private static string _delegateAdminId;
        /// <summary>
        ///     离线获取
        /// </summary>
        /// <param name="context"></param>
        /// <param name="userName"></param>
        /// <returns></returns>
        public static IEnumerable<Role> FindRolesByUserName(this MemberDbContextBase context, string userName)
        {
            var user = context.Users.FirstOrDefault(f => f.NormalizedUserName == userName.ToUpper());
            var query = from role in context.Roles
                        join roleUser in context.UserRoles on role.Id equals roleUser.RoleId
                        where roleUser.UserId == user.Id
                        select role;
            return query.ToList();
        }

        public static IEnumerable<Role> FindRolesByUserId(this MemberDbContextBase context, string userId)
        {
            var query = from role in context.Roles
                        join roleUser in context.UserRoles on role.Id equals roleUser.RoleId
                        where roleUser.UserId == userId
                        select role;
            return query.ToList();
        }

        public static string AdminRoleId(this MemberDbContextBase context)
        {
            if (_adminRoleId == null)
            {
                var uery = from role in context.Roles
                           where role.Name == Role.Admin
                           select role.Id;
                _adminRoleId = uery.FirstOrDefault();
            }

            return _adminRoleId;
        }

        public static User GetByUserName(this MemberDbContextBase context, string userName)
        {
            return context.Users.FirstOrDefault(f => f.NormalizedUserName == userName.ToUpper());
        }

        public static User GetByVendorName(this MemberDbContextBase context, Vendor vendor)
        {
            return context.Users.FirstOrDefault(f => f.Vendor == vendor);
        }

        public static User SystemUser(this MemberDbContextBase context)
        {
            return context.Users.AsNoTracking().FirstOrDefault(f => f.NormalizedUserName == User.System.ToUpper());
        }

        public static string DelegateAdminId(this MemberDbContextBase context)
        {
            if (_adminRoleId == null)
            {
                var uery = from role in context.Roles
                    where role.Name == Role.DelegateAdmin
                    select role.Id;
                _adminRoleId = uery.FirstOrDefault();
            }

            return _adminRoleId;
        }
    }
}